import 'dart:io';

main() {
  print('main start');
  //1
 run();
  //2
  Future<String>(() {
    sleep(Duration(seconds: 2));
    return 'Hello Dart1';
//    throw Exception('我是错误信息1！');
  })
      .then((String value) {
        print(value);
        sleep(Duration(seconds: 2));
        return 'Hello Dart2';
//        throw Exception('我是错误信息2！');
      })
      .then((value) {
        print(value);
        sleep(Duration(seconds: 3));
        return 'Hello Dart3';
      })
      .then((value) => print(value))
      .catchError((err) => print('执行catchError:$err----'))
      .whenComplete(() => print('执行结束!'));

  Future.value('hello dart').then((value) => print(value));
  Future.error('error').catchError((err) => print(err));
  Future.delayed(Duration(seconds: 2))
      .then((value) => 'value')
      .then((value) => print(value));
  print('main end');
}

run() {
  //发送一个网络请求
  var future = getNetworkData();
  print(future);
//  future.then((String value) => print(value))
  future
      .then((String value) => print(value))
      .catchError((err) => print('执行catchError:$err----'))
      .whenComplete(() => print('执行结束!'));
//  future.catchError((err) => print('执行catchError:$err----'));
}

/**
 * 模拟一个网络请求
 */
Future<String> getNetworkData() {
  return Future<String>(() {
    //1.将耗时的操作包裹到Future的回调函数中
    //   只要有返回结果，那么就执行Future对应的then的回调(Promise-resolve)
    //   如果没有结果返回(有错误信息),需要在Future回调中抛出一个异常(Promise-reject)
    sleep(Duration(seconds: 2));
//    return 'Hello Dart';
    throw Exception('我是错误信息！');
  });
}
